<script setup lang="ts">
import OrgUserPicker from "../../OrgUserPicker.vue";
import type { MultiTagsItem } from "../FormComponentMixin";
import type { FormDesignerComponents, FormItemPerm } from "../FormComponentMixin";
import { getDeptList } from "@/api/flow/auditor";
import { isReadonly } from "../FormItem";
import { ref, inject, computed, onMounted, watchEffect } from "vue";

const props = defineProps({
  type: {
    type: String,
    default: ""
  },
  mode: {
    type: String,
    default: "normal" //组件模式，free设计模式，normal 编辑模式, read 阅读模式，disable 禁用模式
  }
});
const _value = defineModel<string>();
const config = defineModel<FormDesignerComponents>("config");
const selections = ref<MultiTagsItem[]>([]);
const orgPickerRef = ref();
const perm = inject<Array<FormItemPerm>>("perm");

const disabled = computed(() => {
  if (props.mode === "disable" && isReadonly(perm, config.value.code)) {
    return true;
  }
  return false;
});

const readonly = computed(() => {
  if (props.mode === "read" || isReadonly(perm, config.value.code)) {
    return true;
  }
  return false;
});

function selectOk(users) {
  selections.value = users;
  _value.value = selections.value
    .map(item => {
      return item.id;
    })
    .join(",");
  orgPickerRef.value.close();
}

const handleOpen = () => {
  orgPickerRef.value.show();
};

onMounted(() => {
  if (config.value.props.defaultLogin) {
    const deptid = "0";
    if (!_value.value) {
      _value.value = deptid;
    }
  } else {
    _value.value = "";
  }
});

const handleReduce = index => {
  selections.value.splice(index, 1);
  _value.value = selections.value
    .map(item => {
      return item.id;
    })
    .join(",");
};

watchEffect(() => {
  if (_value.value && selections.value.length === 0) {
    getDeptList({ id: _value.value }).then(res => {
      if (res.code === 200) {
        selections.value = res.data;
      }
    });
  }
});
</script>

<template>
  <div style="display: flex; align-items: center">
    <el-button icon="plus" round @click="handleOpen" :disabled="disabled" />
    <div class="w-org-items">
      <el-tag
        v-for="(tag, index) in selections"
        :key="tag.id"
        :closable="!readonly"
        type="primary"
        @close="handleReduce(index)"
        style="margin-right: 10px"
      >
        {{ tag.text }}
      </el-tag>
    </div>
    <el-text class="w-placeholder">{{ config.props.placeholder }}</el-text>
    <OrgUserPicker
      ref="orgPickerRef"
      :multiple="config.props.multiple"
      type="dept"
      v-model="selections"
      @ok="selectOk"
    />
  </div>
</template>

<style scoped lang="scss">
.w-placeholder {
  margin-left: 10px;
  color: var(--el-text-color-placeholder);
}
.w-org-items {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: flex-start;
  margin-left: 10px;
}
</style>
